package leetcode101.string_problem;

/**
 * @author Synhard
 * @version 1.0
 * @class KMP
 * @description TODO
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-07-11 15:21
 */
public class KMP {
    public static void main(String[] args) {
        System.out.println(match("ababcabcdababaaaabc", "abcdababaa"));
    }


    public static int[] getNext(String p) {
        int j = -1, i = 0;
        int[] next = new int[p.length()];
        next[0] = -1;
        while (i < p.length() - 1) {
            if (j == -1 || p.charAt(i) == p.charAt(j)) {
                next[++i] = ++j;
                continue;
            }
            j = next[j];
        }
        return next;
    }

    public static int match(String s, String p) {
        int i = 0, j = 0;
        int[] next = getNext(p);
        while (i < s.length() && j < p.length()) {
            if (j == -1 || s.charAt(i) == p.charAt(j)) {
                i++;
                j++;
                continue;
            }
            j = next[j];
        }
        if (j == p.length()) {
            return i - j;
        }
        return -1;
    }

}
